import serial
import serial.tools.list_ports

class mySerial(object):
    def initMySer(self):
        self.ser = serial.Serial()

    def getSerialOrNone(self,port):
        try:
            return serial.Serial(port)
        except:
            return None

    #列出本地的com口
    def listMyCom(self):
        port_list = list(serial.tools.list_ports.comports())
        if len(port_list) == 0:
            print('无可用串口')
            return None
        else:
            serialNamelist=[0 for x in range(len(port_list))]
            for i in range(0,len(port_list)):
                port_list_0 =list(port_list[i])
                serialNamelist[i] = port_list_0[0]+' '+port_list_0[1]
                #print(serialNamelist[i])
            return serialNamelist

    def openSerial(self,port,bsp):
        try:
            if(self.ser.is_open):
                print("%s is open!",self.ser.port)
            else:
                self.ser.port = port
                self.ser.baudrate = bsp
                self.ser.stopbits = 1
                self.ser.parity = 'N' #校验位:N－无校验，E－偶校验，O－奇校验
                self.ser.timeout = 1
                self.ser.open()
                print("串口配置的参数 >", self.ser)
        except Exception as e:
            print("异常 :"+e)

    def closeSerial(self):
        try:
            if(self.ser.is_open):
                self.ser.close()
                print("%s is close!" %(self.ser.port))
            else:
                pass
        except Exception as e:
            print("异常 :"+e)

    def sendATCmd(self,cmd):
        if(self.ser.is_open):
            n = self.ser.write(cmd.encode())
        else:
            print("serial not open !")

    def recvDataAll(self,data):
        if(self.ser.is_open):
            data['data'] = self.ser.read_all()
        else:
            print("serial not open !")

    def recvDataLine(self,data):
        if(self.ser.is_open):
            data['data'] = self.ser.readline()
        else:
            print("serial not open !")
